//外部使用
// var mChart = echarts.init(document.getElementById('km'));
// mChart.setOption(kline.initMOption(data.lindata,'us'));
//
// var kChart = echarts.init(document.getElementById('kl'));
// kChart.setOption(kline.initKOption(data.knedata));



var bgColor = "#fff"; //背景
var bgColor2 = "#f6f7fb"; //黑色背景
var bgColor3 = "#f6f7fb"; //黑色背景

// 白色背景下红涨绿跌
var upColor = "#F9293E"; //涨颜色红色
var downColor = "#00aa3b"; //跌颜色绿色

// 红涨蓝跌
var upColor2 = "#D70101"; //红色
var downColor2 = "#01FFFF"; //蓝色

// 黑色背景下红涨绿跌
var upColor3 = "#F9293E"; //红色
var downColor3 = "#00aa3b"; //绿色

// ma  颜色
var ma5Color = "#39afe6";
var ma10Color = "#da6ee8";
var ma20Color = "#ffab42";
var ma30Color = "#00940b";
// 坐标轴的颜色
var axisLineColor = '#9a9a9f';


// 黑色背景下  颜色
var ma5Color2 = "#9D9D9D";
var ma10Color2 = "#CECF00";
var ma20Color2 = "#CF01CF";
var ma30Color2 = "#038804";
// 坐标轴的颜色
var axisLineColor2 = '#4F0000';

var tabLineColor = '#FF0000';

/**
 * 15:20 时:分 格式时间增加num分钟
 * @param {Object} time 起始时间
 * @param {Object} num
 */
function addTimeStr(time, num) {
  var hour = time.split(':')[0];
  var mins = Number(time.split(':')[1]);
  var mins_un = parseInt((mins + num) / 60);
  var hour_un = parseInt((Number(hour) + mins_un) / 24);
  if (mins_un > 0) {
    if (hour_un > 0) {
      var tmpVal = ((Number(hour) + mins_un) % 24) + "";
      hour = tmpVal.length > 1 ? tmpVal : '0' + tmpVal; //判断是否是一位
    } else {
      var tmpVal = Number(hour) + mins_un + "";
      hour = tmpVal.length > 1 ? tmpVal : '0' + tmpVal;
    }
    var tmpMinsVal = ((mins + num) % 60) + "";
    mins = tmpMinsVal.length > 1 ? tmpMinsVal : 0 + tmpMinsVal; //分钟数为 取余60的数
  } else {
    var tmpMinsVal = mins + num + "";
    mins = tmpMinsVal.length > 1 ? tmpMinsVal : '0' + tmpMinsVal; //不大于整除60
  }
  return hour + ":" + mins;
}

//获取增加指定分钟数的 数组  如 09:30增加2分钟  结果为 ['09:31','09:32']
function getNextTime(startTime, endTIme, offset, resultArr) {
  var result = addTimeStr(startTime, offset);
  resultArr.push(result);
  if (result == endTIme) {
    return resultArr;
  } else {
    return getNextTime(result, endTIme, offset, resultArr);
  }
}


/**
 * 不同类型的股票的交易时间会不同
 * @param {Object} type   hs=沪深  us=美股  hk=港股
 */
var time_arr = function(type) {
  if (type.indexOf('us') != -1) { //生成美股时间段
    var timeArr = new Array();
    timeArr.push('09:30')
    return getNextTime('09:30', '16:00', 1, timeArr);
  } else if (type.indexOf('hs') != -1) { //生成沪深时间段
    var timeArr = new Array();
    timeArr.push('09:30');
    timeArr.concat(getNextTime('09:30', '11:29', 1, timeArr));
    timeArr.push('13:00');
    timeArr.concat(getNextTime('13:00', '15:00', 1, timeArr));
    return timeArr;
  } else if (type.indexOf('hk') != -1) { //生成港股时间段
    var timeArr = new Array();
    timeArr.push('09:30');
    timeArr.concat(getNextTime('09:30', '11:59', 1, timeArr));
    timeArr.push('13:00');
    timeArr.concat(getNextTime('13:00', '16:00', 1, timeArr));
    return timeArr;
  } else {
    return [];
  }

}


const get_m_data = function(m_data, type) {
  const priceArr = new Array();
  const avgPrice = new Array();
  const vol = new Array();
  const times = type == 'auto' ? [] : time_arr(type);
  const datalist = m_data[0];
  // var datalist = m_data['data'];
  // console.log(datalist);
  for (let key in datalist) {
    priceArr.push(datalist[key][1]);
    avgPrice.push(datalist[key][2]);
    vol.push(datalist[key][3]);
    if (type == 'auto') {
      times[key] = datalist[key][0]
    }
  }
  return {
    priceArr: priceArr,
    avgPrice: avgPrice,
    vol: vol,
    times: times
  }
}



//==========================================分时表 option

/**
 * 生成分时option
 * @param {Object} m_data 分时数据
 * @param {Object} type 股票类型  us-美股  hs-沪深  hk-港股
 */
export function initMOption(m_data, type) {
  let klinemax=500;
  if (m_data[0].length > 300 && m_data[0].length < 501) {
    klinemax = 500;
  }
  if (m_data[0].length > 200 && m_data[0].length < 301) {
    klinemax = 400;
  }
  if (m_data[0].length < 201) {
    klinemax = 300;
  }
  var m_datas = get_m_data(m_data, type);
  return {
    tooltip: { //弹框指示器
      trigger: 'axis',
      axisPointer: {
        type: 'cross'
      },
      formatter: function(params, ticket, callback) {
        var i = params[0].dataIndex;

        var color;
        if (m_datas.priceArr[i] > m_data.yestclose) {
          color = 'style="color:#ff4242"';
        } else {
          color = 'style="color:#26bf66"';
        }

        var html = '<div class="commColor" style="width:100px;"><div>当前价 <span  ' + color + ' >' + m_datas.priceArr[i] +
          '</span></div>';
        html += '<div>均价 <span  ' + color + ' >' + m_datas.avgPrice[i] + '</span></div>';
        html += '<div>涨跌 <span  ' + color + ' >' + ratioCalculate(m_datas.priceArr[i], m_data.yestclose) +
          '%</span></div>';
        html += '<div>成交量 <span  ' + color + ' >' + m_datas.vol[i] + '</span></div></div>'
        return html;
      }
    },
    axisPointer: {
      show: true
    },
    color: [ma5Color, ma10Color, ma20Color, ma30Color],
    grid: [{
      id: 'gd1',
      left: '0%',
      right: '1%',
      height: '70%', //主K线的高度,
      top: '2%'
    }, {
      left: '0%',
      right: '1%',
      top: '76.5%',
      height: '16%' //交易量图的高度
    }],
    xAxis:
      //==== x轴
      [{
          type: 'category',
          gridIndex: 0,
          data: m_datas.times,
          axisLabel: { //label文字设置
            show: true,
            color: axisLineColor,
          },
          axisLine: {
            show: true,
            onZero: false,
            lineStyle: {
              color: axisLineColor
            },
          },
          axisTick: {
            // 刻度
            show: false,
          },
          splitLine: {
            show: false,
          },
          splitNumber: klinemax,
          min: 'dataMin',
          max: klinemax
        },
        { //交易量图
          type: 'category',
          gridIndex: 1,
          data: m_datas.times,
          axisLabel: { //label文字设置
            color: axisLineColor,
            fontSize: 10
          },
          splitNumber: klinemax,
          min: 'dataMin',
          max: klinemax
        },
      ],
    yAxis:
      //y轴
      [{

          gridIndex: 0,
          scale: true,
          splitNumber: 3,
          position: 'right',
          axisLine: { //y轴显示
            show: false,
            onZero: false,
          },
          axisLabel: { //label文字设置
            inside: true, //label文字朝内对齐
            fontWeight: 'bold',
            color: function(val) {
              if (val == m_data.yestclose) {
                return '#aaa'
              }
              return val > m_data.yestclose ? upColor : downColor;
            }
          },
          axisTick: { //y轴刻度
            show: false,
          },
          splitLine: { //分割线设置
            show: true,
            lineStyle: {
              color: axisLineColor2,
              type: 'dashed'
            }
          },
        },
        { //交易图
          gridIndex: 1,
          splitNumber: 3,
          z: 4,
          axisLine: {
            onZero: false
          },
          axisTick: {
            show: false
          },
          splitLine: {
            show: false
          },
          axisLabel: { //label文字设置
            color: axisLineColor2,
            inside: true, //label文字朝内对齐
            fontSize: 8
          },
        }
      ],
    dataZoom: [{
      type: 'inside',
      xAxisIndex: [0, 1], //控件联动
      // start: 100,
      // end: 50,
    }],
    animation: false, //禁止动画效果
    backgroundColor: bgColor2,
    blendMode: 'source-over',
    series: [{
        name: '当前价',
        type: 'line',
        data: m_datas.priceArr,
        smooth: true,
        symbol: "none", //中时有小圆点
        lineStyle: {
          normal: {
            opacity: 1,
            color: '#222',
            width: 1
          }
        },
        // areaStyle: {
        //   normal: {
        //     color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [{
        //       offset: 0,
        //       color: 'rgba(255, 255, 255, 0.7)'
        //     }, {
        //       offset: 0.8,
        //       color: 'rgba(255, 255, 255, 0.02)'
        //     }], false),
        //     shadowColor: 'rgba(0, 0, 0, 0.1)',
        //     shadowBlur: 10
        //   }
        // }
      },
      // {
      //   name: '均价',
      //   type: 'line',
      //   data: m_datas.avgPrice,
      //   smooth: true,
      //   symbol: "none", //中时有小圆点
      //   lineStyle: { //标线的样式
      //     normal: {
      //       opacity: 0.5,
      //       color: '#FFFF00',
      //       width: 1
      //     }
      //   }
      // },
      // {
      // 	type: 'line',
      // 	data: m_datas.priceArr,
      // 	smooth: true,
      // 	symbol: "none",
      // 	gridIndex: 1,
      // 	xAxisIndex: 1,
      // 	yAxisIndex: 1,
      // 	lineStyle: { //标线的样式
      // 		normal: {
      // 			width: 0
      // 		}
      // 	}
      // },
      {
        name: 'Volumn',
        type: 'bar',
        xAxisIndex: 1,
        yAxisIndex: 1,
        data: m_datas.vol,
        itemStyle: {
          normal: {
            // color: function(params) {
            // 	var colorList;
            // 	if (m_datas.priceArr[params.dataIndex] > m_datas.priceArr[params.dataIndex - 1]) {
            // 		colorList = upColor;
            // 	} else {
            // 		colorList = downColor;
            // 	}
            // 	return colorList;
            // },
            color: '#FFFF00'
          }
        }
      }
    ]
  };
}



/**
 * 计算价格涨跌幅百分比
 * @param {Object} price 当前价
 * @param {Object} yclose 昨收价
 */
function ratioCalculate(price, yclose) {
  return ((price - yclose) / yclose * 100).toFixed(3);
}









//数组处理
export function splitData(rawData) {
  // var datas = [];
  // var times = [];
  // var vols = [];
  // for (var i = 0; i < rawData.length; i++) {
  //   datas.push(rawData[i]);
  //   // times.push(rawData[i].splice(0, 1)[0]);
  //   // vols.push(rawData[i][4]);
  // }
  //   0       1    2     3     4     5       6
  // [时间，开盘价，收盘，最低，最高，持仓量，成交量]
  const datas = rawData.map(function (item) {
    return [+item[1], +item[2], +item[3], +item[4]];
  });
  const times = rawData.map(function (item) {
    return item[0];
  });
  // 持仓量
  const vols = rawData.map(function (item) {
    return item[5]
  });
  // 成交量
  const chgNum = rawData.map(function (item) {
    return item[6]
  });
  // console.log('times',times);
  // console.log('vols',vols);
  return {
    datas: datas,
    times: times,
    chgNum: chgNum,
    vols: vols
  };
}


//================================MA计算公式
function calculateMA(dayCount, data) {
  var result = [];
  if (data.datas[0][1].toString().split(".")[1] == undefined) {
    var tofix = 2;
  } else {
    var tofix = data.datas[0][1].toString().split(".")[1].length;
  }
  if (tofix == 1) {
    tofix = 2;
  }
  for (var i = 0, len = data.times.length; i < len; i++) {
    if (i < dayCount) {
      result.push('-');
      continue;
    }
    var sum = 0;
    for (var j = 0; j < dayCount; j++) {
      sum += data.datas[i - j][1];
    }
    result.push((sum / dayCount).toFixed(tofix));
  }
  return result;
}


//=================================================MADC计算公式

var calcEMA, calcDIF, calcDEA;

/*
 * 计算EMA指数平滑移动平均线，用于MACD
 * @param {number} n 时间窗口
 * @param {array} data 输入数据
 * @param {string} field 计算字段配置
 */
calcEMA = function (n, data, field) {
  var i, l, ema, a;
  a = 2 / (n + 1);
  if (field) {
    //二维数组
    ema = [data[0][field]];
    for (i = 1, l = data.length; i < l; i++) {
      ema.push((a * data[i][field] + (1 - a) * ema[i - 1]).toFixed(2));
    }
  } else {
    //普通一维数组
    ema = [data[0]];
    for (i = 1, l = data.length; i < l; i++) {
      ema.push((a * data[i] + (1 - a) * ema[i - 1]).toFixed(3));
    }
  }
  return ema;
};

/*
 * 计算DIF快线，用于MACD
 * @param {number} short 快速EMA时间窗口
 * @param {number} long 慢速EMA时间窗口
 * @param {array} data 输入数据
 * @param {string} field 计算字段配置
 */
calcDIF = function(short, long, data, field) {
  var i, l, dif, emaShort, emaLong;
  dif = [];
  emaShort = calcEMA(short, data, field);
  emaLong = calcEMA(long, data, field);
  if (data[0][1].toString().split(".")[1] == undefined) {
    var tofix = 2;
  } else {
    var tofix = data[0][1].toString().split(".")[1].length;
  }
  if (tofix == 1) {
    tofix = 2;
  }
  for (i = 0, l = data.length; i < l; i++) {
    dif.push((emaShort[i] - emaLong[i]).toFixed(tofix));
  }
  return dif;
};

/*
 * 计算DEA慢线，用于MACD
 * @param {number} mid 对dif的时间窗口
 * @param {array} dif 输入数据
 */
calcDEA = function(mid, dif) {
  return calcEMA(mid, dif);
};

/*
 * 计算MACD
 * @param {number} short 快速EMA时间窗口
 * @param {number} long 慢速EMA时间窗口
 * @param {number} mid dea时间窗口
 * @param {array} data 输入数据
 * @param {string} field 计算字段配置
 */
export const calcMACD = function(short, long, mid, data, field) {
  var i, l, dif, dea, macd, result;
  result = {};
  macd = [];
  dif = calcDIF(short, long, data, field);
  dea = calcDEA(mid, dif);
  // if (data[0][1].toString().split(".")[1] == undefined) {
  //   var tofix = 2;
  // } else {
  //   var tofix = data[0][1].toString().split(".")[1].length;
  // }
  // if (tofix == 1) {
  //   tofix = 2;
  // }
  for (i = 0, l = data.length; i < l; i++) {
    macd.push(((dif[i] - dea[i]) * 2).toFixed(3));
  }
  result.dif = dif;
  result.dea = dea;
  result.macd = macd;
  return result;
};


//=================================================MADC计算公式 end

//===============k线
export function initKOption(cdata,nowprice) {
  let startnum, endnum, klinemax;
  klinemax = cdata.length;
  if (cdata.length > 300 && cdata.length < 501) {
    startnum = 100, endnum = 90;
  }
  if (cdata.length > 100 && cdata.length < 301) {
    startnum = 100, endnum = 70;
  }
  if (cdata.length > 50 && cdata.length < 101) {
    startnum = 100, endnum = 50, klinemax = 100;
  }
  if (cdata.length < 51) {
    startnum = 0, endnum = 100, klinemax = 50;
  }
  var data = splitData(cdata);
  var macd = calcMACD(12, 26, 9, data.datas, 1);

  return {
    tooltip: { //提示框组件
      trigger: 'axis',
      axisPointer: {
        type: 'cross'
      },
      // formatter: function(data) {
      //   var htmllist = '<div>';
      //   htmllist += '时间:' + data[0].name + '<br/>';
      //   htmllist += '开盘价:' + data[0].value[1] + '<br/>';
      //   htmllist += '收盘价:' + data[0].value[2] + '<br/>';
      //   htmllist += '最低价:' + data[0].value[3] + '<br/>';
      //   htmllist += '最高价:' + data[0].value[4] + '<br/>';
      //   return htmllist;
      // }
    },
	legend: {
		// data: ['日K', 'MA5', 'MA10', 'MA20', 'MA30'],
		inactiveColor: '#fff',
		textStyle:{
			color:'#222',
			fontSize:10
		},
		left:'2%'
	},
    color: [ma5Color2, ma10Color2, ma20Color2, ma30Color2],
    grid: [{
        id: 'gd1',
        left: '1%',
        right: '1%',
        height: '65%', //主K线的高度,
        top: '2%'
      }, {
        left: '1%',
        right: '1%',
        top: '72%',
        height: '12%' //交易量图的高度
      },
      {
        left: '1%',
        right: '1%',
        top: '86%', //MACD 指标
        height: '12%'
      }
    ],
    xAxis: [{ //主图
        type: 'category',
        data: data.times,
        scale: true,
        boundaryGap: true,
        axisLine: {
          show: true,
          onZero: false,
          // lineStyle: {
          //   color: tabLineColor
          // },
        },
        axisTick: {
          show: true,// 刻度
        },
        axisLabel: { //label文字设置
          color: '#222',
		  fontSize:10,
          inside: false, //label文字朝外对齐
        },
        splitLine: { //分割线设置
          show: false,
          // lineStyle: {
          //   color: axisLineColor2,
          //   type: 'dashed'
          // }
        },
        splitNumber: klinemax,
        min: 'dataMin',
        // max: klinemax
        max: 'dataMax'
      }, { //交易量图
        type: 'category',
        gridIndex: 1,
        data: data.times,
        axisLabel: { //label文字设置
          color: axisLineColor,
          fontSize: 10,
		  show:false
        },
        splitNumber: klinemax,
        min: 'dataMin',
        // max: klinemax,
		max: 'dataMax'
      },
      { //幅图
		  type: 'category',
		  gridIndex: 2,
		  data: data.times,
		  axisLabel: {
			show: false
		  },
		  axisLine: {
			lineStyle: {
			  color: axisLineColor
			},
		  },
		  min: 'dataMin',
		  // max: klinemax,
		  max: 'dataMax'
      },
    ],

    yAxis: [{ //==主图
        show: true,
        scale: true,
        splitNumber: 4,
        position: 'left',
        axisLine: { //y轴显示
          show: false,
          onZero: false,
        },
        axisTick: { //y轴刻度
          show: false,
        },
        axisLabel: { //label文字设置
          show: false,
          color: '#222',
          inside: true, //label文字朝内对齐
          lineStyle: {
            color: axisLineColor2
          }
        },
        splitLine: { //分割线设置
          show: false,
          lineStyle: {
            color: axisLineColor2,
            type: 'dashed'
          }
        },
      }, { //交易图
        gridIndex: 1,
        splitNumber: 3,
        z: 4,
        axisLine: {
          onZero: false
        },
        axisTick: {
          show: false
        },
        splitLine: {
          show: false
        },
        axisLabel: { //label文字设置
          color: '#222',
          inside: true, //label文字朝内对齐
          fontSize: 8
        },
      },
      { //幅图
        z: 4,
        gridIndex: 2,
        splitNumber: 3,
        axisLine: {
          onZero: false
        },
        axisTick: {
          show: false
        },
        splitLine: {
          show: false
        },
        axisLabel: { //label文字设置
          color: '#222',
          inside: true, //label文字朝内对齐
          fontSize: 8
        },
      },
    ],

    dataZoom: [{
      type: 'inside',
      xAxisIndex: [0, 1, 2], //控件联动
      start: 70,
      end: 100,
	  zoomLock:false,
      // rangeMode: ['value', 'percent']
    }],
    animation: false, //禁止动画效果
    backgroundColor: bgColor2,
    blendMode: 'source-over',
    series: [{
        // name: 'K线图',
        type: 'candlestick',
        data: data.datas,
        large: true,
        largeThreshold: 300,
        itemStyle: {
          normal: {
            // color: upColor3, //fd2e2e  ff4242
            // color0: downColor3,
            // borderColor: upColor3,
            // borderColor0: downColor3,
			color: '#FD1050',
			color0: '#0CF49B',
			borderColor: '#FD1050',
			borderColor0: '#0CF49B'
          }
        },
		roam: true, // 开启区域缩放和平移功能
		// markLine: {
		//   symbol: ['none', 'none'], // none为标线两端的样式为无，可更改
		//   data: [
		//     {
		//       silent: false,
		//       yAxis: nowprice,  // 警戒线位置
		//       label: {
		//         position: 'insideStart', // 文字位置
		//         //formatter: '当前价格',  //文字
		//         color: '#fff'  // 文字颜色
		//       },
		//       lineStyle: { type: 'dashed', color: '#c23531', width: 1 } // 样式： 线型、颜色、线宽
		//     }
		//   ]
		// },
      }, {
        name: 'MA5',
        type: 'line',
        data: calculateMA(5, data),
        smooth: true,
        symbol: "none", //线条样式
        lineStyle: {
          normal: {
            opacity: 0.8,
            color: ma5Color2,
            width: 1
          }
        },
      },
      {
        name: 'MA10',
        type: 'line',
        data: calculateMA(10, data),
        smooth: true,
        symbol: "none",
        lineStyle: { //标线的样式
          normal: {
            opacity: 0.8,
            color: ma10Color2,
            width: 1
          }
        }
      },
      {
        name: 'MA20',
        type: 'line',
        data: calculateMA(20, data),
        smooth: true,
        symbol: "none",
        lineStyle: {
          opacity: 0.8,
          width: 1,
          color: ma20Color2
        }
      },
      {
        name: 'MA30',
        type: 'line',
        data: calculateMA(30, data),
        smooth: true,
        symbol: "none",
        lineStyle: {
          normal: {
            opacity: 0.8,
            width: 1,
            color: ma30Color2
          }
        }
      },
	  {
	    name: 'Position',
	    type: 'bar',
	    symbol: "none",
	    xAxisIndex: 1,
	    yAxisIndex: 1,
		 barWidth: '40%',
	    data: data.vols,  //持仓量
	    itemStyle: {
	      normal: {
	        color: function (params) {
	          var colorList;
	          if (params.data >= 0) {
	            colorList = upColor;
	          } else {
	            colorList = downColor;
	          }
	          return colorList;
	        },
	      }
	    }
	  },
	  {
	    name: 'Turnover',
	    type: 'line',
	    symbol: "none",
	    xAxisIndex: 2,
	    yAxisIndex: 2,
	    data: data.chgNum,  //成交量
	    lineStyle: {
	      normal: {
	        color: ma5Color2,
	        width: 1
	      }
	    }
	  },
      {
        name: 'MACD',
        type: 'bar',
        xAxisIndex: 2,
        yAxisIndex: 2,
        data: macd.macd,
        barWidth: '40%',
        itemStyle: {
          normal: {
            color: function (params) {
              var colorList;
              if (params.data >= 0) {
                colorList = upColor;
              } else {
                colorList = downColor;
              }
              return colorList;
            },
          }
        }
      }, {
        name: 'DIF',
        type: 'line',
        symbol: "none",
        xAxisIndex: 2,
        yAxisIndex: 2,
        data: macd.dif,
        lineStyle: {
          normal: {
            // color: '#da6ee8',
            width: 1
          }
        }
      }, {
        name: 'DEA',
        type: 'line',
        symbol: "none",
        xAxisIndex: 2,
        yAxisIndex: 2,
        data: macd.dea,
        lineStyle: {
          normal: {
            opacity: 0.8,
            // color: '#39afe6',
            width: 1
          }
        }
      },
      // {
      //   name: 'MACD',
      //   type: 'bar',
      //   z: 4,
      //   xAxisIndex: 2,
      //   yAxisIndex: 2,
      //   data: macd.macd,
      //   itemStyle: {
      //     normal: {
      //       color: function(params) {
      //         var colorList;
      //         if (params.data >= 0) {
      //           colorList = upColor2;
      //         } else {
      //           colorList = downColor2;
      //         }
      //         return colorList;
      //       },
      //     }
      //   },
      // },

      // {
      //   name: 'DEA',
      //   type: 'line',
      //   symbol: "none",
      //   xAxisIndex: 2,
      //   yAxisIndex: 2,
      //   data: macd.dea,
      //   lineStyle: {
      //     normal: {
      //       opacity: 0.8,
      //       color: ma10Color2,
      //       width: 1
      //     }
      //   }
      // }
    ]
  };


}

export default {
  initMOption,
  initKOption,
  splitData,
  calcMACD
}
